package com.app.studyroom.adapter;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.app.studyroom.R;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.ssrApproval.ApprovalCompleteRequest;
import com.app.studyroom.api.model.ssrGet.ApprovalTaskResponse;
import com.app.studyroom.dialog.CustomSizeDialog;
import com.google.gson.Gson;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ApprovalTaskAdapter extends RecyclerView.Adapter<ApprovalTaskAdapter.ViewHolder> {

    private Context context;
    private List<ApprovalTaskResponse> taskList;
    private final TaskRefreshCallback refreshCallback;


    public ApprovalTaskAdapter(Context context, List<ApprovalTaskResponse> taskList, TaskRefreshCallback refreshCallback) {
        this.context = context;
        this.taskList = taskList;
        this.refreshCallback = refreshCallback;
    }


    public interface TaskRefreshCallback {
        void refreshToFirstPage();
    }

    public void updateTaskList(List<ApprovalTaskResponse> list) {
        this.taskList = list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context)
                .inflate(R.layout.item_approval_task, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ApprovalTaskResponse task = taskList.get(position);
        holder.tvTaskName.setText(task.getName());

        // 同意按钮：直接调用 handleApproval，理由为空
        holder.btnAgree.setOnClickListener(v ->
                handleApproval(task.getId(), task.getProcessInstanceId(), true, "")
        );

        // 拒绝按钮：弹出对话框输入理由
        holder.btnReject.setOnClickListener(v -> showRejectReasonDialog(task));
    }


    @Override
    public int getItemCount() {
        return taskList != null ? taskList.size() : 0;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvTaskName, tvAssignee, tvProcessId;
        Button btnAgree, btnReject;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTaskName = itemView.findViewById(R.id.tvTaskName);
//            tvAssignee = itemView.findViewById(R.id.tvAssignee);
//            tvProcessId = itemView.findViewById(R.id.tvProcessId);
            btnAgree = itemView.findViewById(R.id.btnAgree);
            btnReject = itemView.findViewById(R.id.btnReject);
        }
    }
    private void handleApproval(String taskId, String processInstanceId, boolean approve, String reason) {
        SharedPreferences sp = context.getSharedPreferences("Session", Context.MODE_PRIVATE);
        String token = sp.getString("token", null);

        if (token == null || processInstanceId == null) {
            Toast.makeText(context, "参数不完整，审批失败", Toast.LENGTH_SHORT).show();
            return;
        }

        ApprovalCompleteRequest request = new ApprovalCompleteRequest(taskId, approve, reason, processInstanceId);
        String jsonRequest = new Gson().toJson(request);
        android.util.Log.d("ApprovalRequest", "请求体：" + jsonRequest);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.completeApproval(token, request).enqueue(new Callback<ApiResponse<Object>>() {
            @Override
            public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(context, "操作成功", Toast.LENGTH_SHORT).show();
                    if (refreshCallback != null) refreshCallback.refreshToFirstPage();
                } else {
                    Toast.makeText(context, "HTTP失败：" +
                            (response.body() != null ? response.body().getMessage() : "未知错误"), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                Toast.makeText(context, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void showRejectReasonDialog(ApprovalTaskResponse task) {
        CustomSizeDialog dialog = new CustomSizeDialog(context, R.layout.dialog_reject_reason, 0.388f, 0.28f);
        dialog.show();

        EditText editReason = dialog.findViewById(R.id.editRejectReason);
        Button btnConfirm = dialog.findViewById(R.id.btn_confirm);
        Button btnCancel = dialog.findViewById(R.id.btn_cancel);

        btnConfirm.setOnClickListener(v -> {
            String reason = editReason.getText().toString().trim();
            handleApproval(task.getId(), task.getProcessInstanceId(), false, reason);
            dialog.dismiss();
        });

        btnCancel.setOnClickListener(v -> dialog.dismiss());
    }



}
